﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IMES.Common.Infrastructure
{
    public class BaseRepositorys<T> : IBaseRepositorys<T> where T : class
    {
        private readonly IFreeSql _db;
        public BaseRepositorys(IFreeSql db)
        {
            _db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Add(T entity) => _db.Insert(entity).ExecuteAffrows();
        /// <summary>
        /// 异步添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<int> AddAsync(T entity) => _db.Insert(entity).ExecuteAffrowsAsync();
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public Task<int> AddRange(List<T> entitys) => _db.Insert(entitys).ExecuteAffrowsAsync();

        public IDisposable BeginTransaction()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll() => _db.Select<T>().ToList().AsQueryable();
        /// <summary>
        /// 同步更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(T entity) => _db.Update<T>().SetSource(entity).ExecuteAffrows();

        /// <summary>
        /// 异步更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T entity) => await _db.Update<T>()
                            .SetSource(entity)  // 设置需要更新的数据
                            .ExecuteAffrowsAsync(); // 执行更新并返回受影响的行数
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int UpdateRange(List<T> entitys) => _db.Update<T>()
               .SetSource(entitys) // 批量更新
               .ExecuteAffrows(); // 执行并返回受影响的行数
    }
}
